#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>

#include "libradarssd.h"

unsigned long elapsed(struct timeval* begin, struct timeval* end){
    long seconds = end->tv_sec - begin->tv_sec;
    long microseconds = end->tv_usec - begin->tv_usec;
    return seconds*1e6 + microseconds;
}

int main(){
    struct timeval begin, end, slot_head, now; //slot_head和now用于计算实时IOPS

    srand((unsigned)time(NULL));

    gettimeofday(&begin, 0);

    unsigned int GB = 1;
    u64 test_time = 50000;
    u64 max_toa = 7267999178;
    //u64 max_toa = GB*44738560 - TOA_READ_COUNT;
    u64 read_signal = 0;
    unsigned io_finished_in_slot = 0;

    open_unvme();
    gettimeofday(&slot_head, 0);
    for(int i=0;i<test_time;i++){
        //ftype toa_start = rand() % max_toa;
        ftype toa_start = ((u64)rand()*10) % 7267568690;
        //ftype toa_start = 10000000;
        ftype* toa_result = read_signal_dword_unopen(toa_start,TOA_READ_COUNT);
        //printf("toa_start=%lu: %lu %lu %lu %lu\n",toa_start,toa_result[0],toa_result[1],toa_result[2047],toa_result[2048]);
        read_signal += TOA_READ_COUNT;
        io_finished_in_slot += 1;
        //判断时间片
        gettimeofday(&now, 0);
        unsigned elapse = elapsed(&slot_head, &now)/1000000;
        if(elapse>=1){
            printf("IOPS:%u\n",io_finished_in_slot);
            io_finished_in_slot=0;
            gettimeofday(&slot_head, 0);
        }
    }
    close_unvme();
    gettimeofday(&end, 0);

    printf("total elapsed %lu us(%.3f s)\n",elapsed(&begin, &end),elapsed(&begin, &end)/1000000.0);
    float MB = read_signal*FEATURE_SIZE / (float)(1024*1024);
    float bandwith = MB/((double)elapsed(&begin, &end)/1000000);
    double average_latency = (double)elapsed(&begin, &end)/read_signal;
    printf("Read %lu signals in %.2f MB\nBandwith:%.2f MB/s\nAverage latency per-signal:%.4lf us/signal\n",read_signal,MB,bandwith,average_latency);

    return 0;
}